package com.coisshi.base.common.utils;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.io.File;

/**
 * 邮件工具类：支持发送文本邮件和 HTML 邮件
 */
@Slf4j
@Component
public class MailUtil {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送文本邮件
     *
     * @param to      收件人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendTextMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        mailSender.send(message);
        log.info("文本邮件发送成功：{}", to);
    }

    /**
     * 发送 HTML 格式邮件
     *
     * @param to      收件人
     * @param subject 邮件主题
     * @param content HTML 内容
     */
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); // 第二个参数表示是HTML

            mailSender.send(mimeMessage);
            log.info("HTML邮件发送成功：{}", to);
        } catch (MessagingException e) {
            log.error("发送HTML邮件失败", e);
            throw new RuntimeException("发送邮件失败：" + e.getMessage(), e);
        }
    }

    /**
     * 发送带附件的邮件（可选扩展）
     */
    public void sendMailWithAttachment(String to, String subject, String content, File file) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource resource = new FileSystemResource(file);
            helper.addAttachment(file.getName(), resource);

            mailSender.send(mimeMessage);
            log.info("带附件邮件发送成功：{}", to);
        } catch (MessagingException e) {
            log.error("发送带附件邮件失败", e);
            throw new RuntimeException("发送邮件失败：" + e.getMessage(), e);
        }
    }
}

